/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.gateway.server.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.base.domain.constant.CommonConstant.ApiSignConstant;
import com.iwindplus.base.domain.constant.CommonConstant.NumberConstant;
import com.iwindplus.base.domain.dto.MessageBaseDTO;
import com.iwindplus.base.domain.enums.BaseEnum;
import com.iwindplus.base.domain.enums.BizCodeEnum;
import com.iwindplus.base.domain.enums.OperateTypeEnum;
import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.base.domain.vo.ApiSignVO;
import com.iwindplus.base.util.ApiSignUtil;
import com.iwindplus.base.util.HttpsUtil;
import com.iwindplus.base.util.ReactorUtil;
import com.iwindplus.base.util.UrlUtil;
import com.iwindplus.base.util.domain.dto.ApiSignVerifyDTO;
import com.iwindplus.gateway.server.client.MgtClient;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.FilterConstant;
import com.iwindplus.gateway.server.domain.property.GatewayProperty;
import com.iwindplus.gateway.server.util.GatewayUtil;
import java.time.Duration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
 * API签名过滤器.
 *
 * @author zengdegui
 * @since 2020/4/15
 */
@Slf4j
@Component
public class ApiSignFilter implements Ordered, GlobalFilter {

    private static final List<String> DEFAULT_IGNORED_APIS =
        List.of(
            "/static/**",
            "/v3/api-docs",
            "/doc.html",
            "/actuator/**",
            "/imWs/ws"
        );

    private final GatewayProperty property;
    private final MgtClient mgtClient;
    private final AtomicReference<Map<String, ApiSignVO>> snapshot = new AtomicReference<>(Map.of());

    public ApiSignFilter(GatewayProperty property, MgtClient mgtClient) {
        this.property = property;
        this.mgtClient = mgtClient;
    }

    @Override
    public int getOrder() {
        return FilterConstant.FILTER_API_SIGN_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 开关未启用跳过当前过滤器
        if (skip(exchange)) {
            return chain.filter(exchange);
        }

        final long start = System.nanoTime();

        return this.checkApiSign(exchange)
            .then(chain.filter(exchange))
            .doFinally(signal -> log.info("{} execute cost={} ms", this.getClass().getSimpleName(),
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
    }

    private boolean skip(ServerWebExchange exchange) {
        if (Boolean.FALSE.equals(property.getApiSign().getEnabled())) {
            return true;
        }

        String path = exchange.getRequest().getPath().value();
        Set<String> patterns = new HashSet<>(DEFAULT_IGNORED_APIS);
        List<String> custom = property.getApiSign().getIgnoredApi();
        if (CollUtil.isNotEmpty(custom)) {
            patterns.addAll(custom);
        }
        return UrlUtil.isMatchLike(patterns.stream().distinct().toList(), path);
    }

    private Mono<Void> checkApiSign(ServerWebExchange exchange) {
        return this.buildApiSign(exchange)
            .flatMap(dto ->
                this.loadApiSign(dto.getAccessKey())
                    .flatMap(apiSign -> {
                        if (apiSign == null) {
                            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.CONFIG_NOT_EMPTY.getBizStatus())
                                .then(Mono.error(new BizException(BizCodeEnum.CONFIG_NOT_EMPTY)));
                        }
                        dto.setSecretKey(apiSign.getSecretKey());
                        dto.setTimeout(Duration.ofMinutes(apiSign.getTimeout()));

                        if (!ApiSignUtil.verifySign(dto)) {
                            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.INVALID_SIGN.getBizStatus())
                                .then(Mono.error(new BizException(BizCodeEnum.INVALID_SIGN)));
                        }
                        return Mono.empty();
                    }));
    }

    private Mono<ApiSignVerifyDTO> buildApiSign(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders headers = request.getHeaders();
        String path = property.getApiSign().getEnabledRelativePath()
            ? headers.getFirst(ApiSignConstant.X_PATH)
            : request.getPath().value();

        String accessKey = headers.getFirst(ApiSignConstant.X_ACCESS_KEY);
        String timestamp = headers.getFirst(ApiSignConstant.X_TIMESTAMP);
        String nonce = headers.getFirst(ApiSignConstant.X_NONCE);
        String sign = headers.getFirst(ApiSignConstant.X_SIGN);

        if (CharSequenceUtil.isBlank(accessKey)) {
            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.ACCESS_KEY_NOT_EXIST.getBizStatus())
                .then(Mono.error(new BizException(BizCodeEnum.ACCESS_KEY_NOT_EXIST)));
        }
        if (CharSequenceUtil.isBlank(timestamp)) {
            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.TIMESTAMP_NOT_EXIST.getBizStatus())
                .then(Mono.error(new BizException(BizCodeEnum.TIMESTAMP_NOT_EXIST)));
        }
        if (CharSequenceUtil.isBlank(nonce) || nonce.length() < NumberConstant.NUMBER_TEN) {
            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.INVALID_NONCE.getBizStatus())
                .then(Mono.error(new BizException(BizCodeEnum.INVALID_NONCE)));
        }
        if (CharSequenceUtil.isBlank(sign)) {
            return GatewayUtil.asyncPublishErrorLog(exchange, property.getLog(), BizCodeEnum.SIGN_NOT_EXIST.getBizStatus())
                .then(Mono.error(new BizException(BizCodeEnum.SIGN_NOT_EXIST)));
        }

        Map<String, Object> params = new HashMap<>(16);
        params.putAll(request.getQueryParams().toSingleValueMap());
        return ReactorUtil.getRequestBodyByAttr(exchange)
            .flatMap(dto -> {
                String body = dto.getRequestBody();
                if (CharSequenceUtil.isBlank(body)) {
                    return Mono.empty();
                }
                return Mono.just(body);
            })
            .map(body -> HttpsUtil.getByStr(body, true))
            .doOnNext(params::putAll)
            .then(Mono.just(ApiSignVerifyDTO.builder()
                .accessKey(accessKey)
                .timestamp(timestamp)
                .nonce(nonce)
                .sign(sign)
                .path(path)
                .method(request.getMethod().name())
                .params(params)
                .build()));
    }

    private Mono<ApiSignVO> loadApiSign(String accessKey) {
        ApiSignVO cached = snapshot.get().get(accessKey);
        if (cached != null) {
            return Mono.just(cached);
        }
        // 缓存未命中 -> 远程加载 -> 刷新快照
        return mgtClient.getByAccessKey(accessKey)
            .doOnNext(vo -> casRefresh(snapshot, m -> m.put(vo.getAccessKey(), vo)))
            .doOnNext(vo -> log.info("API签名配置加载完成"))
            .subscribeOn(Schedulers.boundedElastic());
    }

    private <K, V> void casRefresh(AtomicReference<Map<K, V>> ref, Consumer<Map<K, V>> modifier) {
        Map<K, V> oldMap, newMap;
        do {
            oldMap = ref.get();
            newMap = new HashMap<>(oldMap);
            modifier.accept(newMap);
        } while (!ref.compareAndSet(oldMap, newMap));
    }

    /**
     * 刷新API签名配置.
     *
     * @param message 消息
     */
    public void refreshAppCert(MessageBaseDTO<List<ApiSignVO>> message) {
        if (Objects.isNull(message) || Objects.isNull(message.getOperateType()) || CollUtil.isEmpty(message.getData())) {
            return;
        }

        final OperateTypeEnum operateType = BaseEnum.fromValue(message.getOperateType(), OperateTypeEnum.class);
        Map<String, ApiSignVO> delta = message.getData().stream()
            .collect(Collectors.toMap(ApiSignVO::getAccessKey, Function.identity()));
        casRefresh(snapshot, m -> {
            switch (operateType) {
                case ADD:
                case MODIFY:
                    m.putAll(delta);
                    break;
                case DELETE:
                    delta.keySet().forEach(m::remove);
                    break;
                default:
                    throw new BizException(BizCodeEnum.UNSUPPORTED_TYPE, new Object[]{message.getOperateType()});
            }
        });

        log.info("API签名配置刷新完成，条目数={}", snapshot.get().size());
    }
}